#include "../lib_include/ProcessInfo.h"
#include "../lib_include/CurrentThread.h"
#include "../lib_include/FileUtil.h"

#include <algorithm>

#include <assert.h>
#include <dirent.h>
#include <pwd.h>
#include <stdio.h> // snprintf
#include <stdlib.h>
#include <unistd.h>
#include <sys/resource.h>
#include <sys/times.h>

namespace netlib
{
namespace detail
{

__thread int t_numOpenedFiles = 0; // 统计一共打开了多少个文件

int fdDirFilter(const struct dirent* d)
{
    if (::isdigit(d->d_name[0]))
        ++t_numOpenedFiles;
    return 0;
}

__thread std::vector<pid_t>* t_pids = NULL;

int taskDirFilter(const struct dirent* d)
{
    if (::isdigit(d->d_name[0]))
        t_pids->push_back(atoi(d->d_name));
    return 0;
}

int scanDir(const char *dirpath, int (*filter)(const struct dirent *))
{
    struct dirent** namelist = NULL;
    int result = ::scandir(dirpath, &namelist, filter, alphasort);
    assert(namelist == NULL);
    return result;
}

Timestamp g_startTime = Timestamp::now(); // 获得进程启动时间

int g_clockTicks = static_cast<int>(::sysconf(_SC_CLK_TCK)); // 获取时钟频率
int g_pageSize = static_cast<int>(::sysconf(_SC_PAGE_SIZE)); // 获取内存页大小

} // namespace detail end

} // namespace netlib end

using namespace netlib;
using namespace netlib::detail;

pid_t ProcessInfo::pid() // 返回pid
{
    return ::getpid();
}

string ProcessInfo::pidString() // 返回pid的字符串形式
{
    char buf[32];
    snprintf(buf, sizeof buf, "%d", pid());
    return buf;
}

uid_t ProcessInfo::uid() // 返回uid
{
    return ::getuid();
}

string ProcessInfo::username() // 返回用户名
{
    struct passwd pwd;
    struct passwd* result = NULL;
    char buf[8192];
    const char* name = "unknownuser";

    getpwuid_r(uid(), &pwd, buf, sizeof buf, &result);
    if (result)
        name = pwd.pw_name;
    return name;
}

uid_t ProcessInfo::euid() // 返回euid
{
    return ::geteuid();
}

Timestamp ProcessInfo::startTime() // 开始计时
{
    return g_startTime;
}

int ProcessInfo::clockTicksPerSecond() // 返回一秒的时钟数
{
    return g_clockTicks;
}

int ProcessInfo::pageSize() // 返回内存页大小
{
    return g_pageSize;
}

bool ProcessInfo::isDebugBuild() // 是否开启调式模式
{
    #ifdef NDEBUG
    return false;
    #else
    return true;
    #endif
}

string ProcessInfo::hostname() // 返回本地主机的标准主机名
{
    char buf[256];
    if (::gethostname(buf, sizeof buf) == 0)
    {
        buf[sizeof(buf)-1] = '\0';
        return buf;
    }
    else
        return "unknownhost";
}

string ProcessInfo::procname()
{
    return procname(procStat()).as_string();
}

StringPiece ProcessInfo::procname(const string& stat)
{
    StringPiece name;
    size_t lp = stat.find('(');
    size_t rp = stat.rfind(')');
    if (lp != string::npos && rp != string::npos && lp < rp)
        name.set(stat.data()+lp+1, static_cast<int>(rp-lp-1));
    return name;
}

string ProcessInfo::procStatus() // 读取进程状态
{
    string result;
    FileUtil::readFile("/proc/self/status", 65536, &result);
    return result;
}

string ProcessInfo::procStat() // 获取进程相关信息
{
    string result;
    FileUtil::readFile("/proc/self/stat", 65536, &result);
    return result;
}

string ProcessInfo::threadStat() // 获取线程相关信息
{
    char buf[64];
    snprintf(buf, sizeof buf, "/proc/self/task/%d/stat", CurrentThread::tid());
    string result;
    FileUtil::readFile(buf, 65536, &result);
    return result;
}

string ProcessInfo::exePath() // 执行路径，从根目录开始的绝对路径
{
    string result;
    char buf[1024];
    ssize_t n = ::readlink("/proc/self/exe", buf, sizeof buf);
    if (n > 0)
    {
        result.assign(buf, n);
    }
    return result;
}

int ProcessInfo::openedFiles() // 返回统计的进程打开的文件数目
{
    t_numOpenedFiles = 0;
    scanDir("/proc/self/fd", fdDirFilter);
    return t_numOpenedFiles;
}

int ProcessInfo::maxOpenFiles() // 查询进程允许打开的最大文件数
{
    struct rlimit rl;
    if (::getrlimit(RLIMIT_NOFILE, &rl))
        return openedFiles();
    else
        return static_cast<int>(rl.rlim_cur);
}

ProcessInfo::CpuTime ProcessInfo::cpuTime() // 获取CPU时间
{
    ProcessInfo::CpuTime t;
    struct tms tms;
    if (::times(&tms) >= 0)
    {
        const double hz = static_cast<double>(clockTicksPerSecond());
        t.userSeconds = static_cast<double>(tms.tms_utime) / hz;
        t.systemSeconds = static_cast<double>(tms.tms_stime) / hz;
    }
    return t;
}

int ProcessInfo::numThreads() // 返回线程数目
{
    int result = 0;
    string status = procStatus();
    size_t pos = status.find("Threads:");
    if (pos != string::npos)
        result = ::atoi(status.c_str() + pos + 8);
    return result;
}

std::vector<pid_t> ProcessInfo::threads() // 返回线程id
{
    std::vector<pid_t> result;
    t_pids = &result;
    scanDir("/proc/self/task", taskDirFilter);
    t_pids = NULL;
    std::sort(result.begin(), result.end());
    return result;
}

